package com.suzhe.ymall.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.suzhe.ymall.common.annotation.LoginAuth;
import com.suzhe.ymall.common.pojo.ApiResEntity;
import com.suzhe.ymall.common.pojo.SysLoginUser;
import com.suzhe.ymall.common.utils.*;

import com.suzhe.ymall.system.param.SysUserQueryParam;
import com.suzhe.ymall.system.pojo.SysUser;
import com.suzhe.ymall.system.pojo.SysUserInfo;
import com.suzhe.ymall.system.pojo.SysUserRole;
import com.suzhe.ymall.system.service.ISysResourceService;
import com.suzhe.ymall.system.service.ISysUserRoleService;
import com.suzhe.ymall.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 系统用户 前端控制器
 * </p>
 *
 * @author suzhe
 * @since 2019-06-05
 */
@RestController
@RequestMapping("/sys/user")
@Slf4j
public class SysUserController {

    @Autowired
    ISysUserService iSysUserService;

    @Autowired
    ISysResourceService iSysResourceService;

    @Autowired
    ISysUserRoleService iSysUserRoleService;

    @Autowired
    RedisTemplateUtils redisTemplateUtils;

    @GetMapping("/list")
    public ApiResEntity list(SysUserQueryParam queryParam) {
        Integer pageNo = queryParam.getPageNo();
        Integer pageSize = queryParam.getPageSize();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(queryParam.getUsername())){
            queryWrapper.eq("username",queryParam.getUsername());
        }
        if (queryParam.getStatus() != null){
            queryWrapper.eq("status",queryParam.getStatus());
        }
        IPage<SysUser> page = iSysUserService.page(new Page<>(pageNo, pageSize),queryWrapper);
        return ApiResEntity.ok(page);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    public ApiResEntity login(@RequestBody SysUser sysUser) {
        log.debug("sys login params:{}", sysUser);
        SysUser user = iSysUserService.getOne(new QueryWrapper<SysUser>().eq("username", sysUser.getUsername()));
        String encryptPassword = PasswordUtils.getEncryptPassword(sysUser.getPassword(), user.getSalt());
        if (user != null && user.getPassword().equals(encryptPassword)) {
            SysLoginUser loginUser = new SysLoginUser();
            loginUser.setId(user.getId())//
                    .setUsername(user.getUsername())//
                    .setEmail(user.getEmail())//
                    .setMobile(user.getMobile());
            String token = YMStringUtils.getUUID();
            String tokenKey = RedisKeys.getTokenKeyForSys(token);
            redisTemplateUtils.set(tokenKey, loginUser, YMConstant.MANAGE_TOKEN_EXPIRE_TIME);
            return ApiResEntity.ok(token);
        }
        return ApiResEntity.error("密码输入错误");
    }


    @GetMapping("/info")
    @LoginAuth
    public ApiResEntity info() {
        SysLoginUser sysLoginUser = LoginUserUtils.getSysLoginUser();
        Set<String> menuPerms = iSysResourceService.getMenuPerms(sysLoginUser.getId());
        Set<String> actionPerms = iSysResourceService.getActionPerms(sysLoginUser.getId());
        SysUserInfo userInfo = new SysUserInfo()//
                .setMenuPerms(menuPerms)//
                .setActionPerms(actionPerms)//
                .setLoginUser(sysLoginUser);
        return ApiResEntity.ok(userInfo);
    }

    @PostMapping("/logout")
    public ApiResEntity logout(HttpServletRequest request) {
        String accessToken = request.getHeader(YMConstant.ACCESS_TOKEN);
        String tokenKey = RedisKeys.getTokenKeyForSys(accessToken);
        redisTemplateUtils.del(tokenKey);
        return ApiResEntity.ok();
    }


    @PostMapping("/save")
    public ApiResEntity save(@RequestBody SysUser sysUser) {
        log.debug("sysUser:{}", sysUser);
        String salt = YMStringUtils.createRandom(false, 6);
        sysUser.setSalt(salt);
        String encryptPassword = PasswordUtils.getEncryptPassword(sysUser.getPassword(), sysUser.getSalt());
        sysUser.setPassword(encryptPassword);
        iSysUserService.saveUser(sysUser);
        return ApiResEntity.ok();
    }

    @GetMapping("/listRole")
    public ApiResEntity listRole(SysUser sysUser) {
        log.debug("sysUser:{}", sysUser);
        List<SysUserRole> sysUserRoles = iSysUserRoleService.list(  //
                new QueryWrapper<SysUserRole>().eq("user_id", sysUser.getId()));
        return ApiResEntity.ok(sysUserRoles);
    }

}
